<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: #222;
        }

        .con {
            list-style: none;
            padding: 0;
        }

        .item {
            height: 50px;
            background-color: aquamarine;
            line-height: 50px;
            border-radius: 10px;
            margin: 5px 0;
            cursor: move;
        }

        .moving {
            border: 2px dashed #aaa;
            background-color: transparent;
            color: transparent;
        }
    </style>
</head>

<body>
    <ul class="con">
        <li draggable="true" class="item">AAA</li>
        <li draggable="true" class="item">BBB</li>
        <li draggable="true" class="item">CCC</li>
        <li draggable="true" class="item">DDD</li>
        <li draggable="true" class="item">EEE</li>
    </ul>
</body>
<script src="./js/Flip.js"></script>
<script>
    let con = document.querySelector(".con");
    let f = new Flip(con.children)
    let sourceNode = null; //拖拽的那个元素
    // 拖拽开始的时候
    con.ondragstart = (ev) => {
        setTimeout(() => {
            sourceNode = ev.target;
            sourceNode.classList.add("moving");
        }, 0)
        f.init()
    }
    //拖拽进入到某个元素上的时候
    con.ondragenter = (ev) => {

        // 如果进入的目标元素是父元素或自身，阻止代码向下执行
        if (ev.target == con || ev.target == sourceNode) {
            return;
        }
        let childs = Array.from(con.children); //所有子节点
        let targetNodeIdx = childs.indexOf((ev.target)) //触碰到的那个元素的下标
        let sourceNodeIdx = childs.indexOf((sourceNode)) //自身的下标
        if (sourceNodeIdx < targetNodeIdx) {
            console.log("向下拖动");
            con.insertBefore(sourceNode, ev.target.nextElementSibling) //将自身插入到目标元素的后边
        } else {
            console.log("向上拖动");
            con.insertBefore(sourceNode, ev.target) //将自身插入到目标元素位置
        }
    }
    // 拖拽结束的时候
    con.ondragend = (ev) => {
        f.play();
        ev.target.classList.remove("moving")
    }
</script>

</html>